<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Crypt;
use Hash;
use DB;

class UserController extends Controller
{
    //add
    public function add()
    {
        return view('admin.user.add', ['title' => '用户添加']);
    }

    // insert
    public function insert(Request $request)
    {
        // dd($request -> all());
        // return 111;
        $this->validate($request, [
                'name' => 'required|min:6|max:18',
                'email' => 'required|email',
                'password' => 'required',
                'rpassword' => 'required|same:password'
            ],[
                'name.required' => '用户名不能为空',
                'name.min' => '用户名最少为6位',
                'name.max' => '用户名最多为18位',
                'email.required' => '邮箱不能为空',
                'email.email' => '邮箱格式不正确',
                'password.required' => '密码不能为空',
                'rpassword.required' => '确认密码不能为空',
                'rpassword.same' => '确认密码不一致'
            ]);//验证信息


        $data = $request -> except('_token', 'rpassword');

        // 处理密码字段
        $data['password'] = Crypt::encrypt($data['password']);
        // // dd($data);//取消token显示
        // $p = Crypt::decrypt($data['password']);

        // $data['password'] = Hash::make($data['password']);//加密
        // dd($data['password']);

        // $res = Hash::check('aaaaaa', '$2y$10$5qZpQGYPL5a7KIpSeQCx/uZp5JJan03u3AH73EVRgzUB2xNajKUOe');//解密
        // dd($res);
        // 处理status字段
        $data['status'] = 0;
        // 处理token字段
        $data['remember_token'] = str_random(50);

        // 处理时间
        $time = time();
        $data['created_at'] = $time;
        $data['updated_at'] = $time;

        // 处理头像
        if($request -> hasfile('pic'))
        {
            if($request -> file('pic') -> isValid())
            {
                $suffix = $request -> file('pic') -> getClientOriginalExtension();
                $fileName = time().mt_rand(10000,99999).'.'.$suffix;
                // 移动文件
                if(!file_exists('./uploads/yhtx'))
                {
                    mkdir('./uploads/yhtx', true, '777');
                }
                $move = $request -> file('pic') -> move('./uploads/yhtx',$fileName);

                if($move)
                {
                    $data['pic'] = $fileName;
                }else{
                    $data['pic'] = 'default.jpg';
                }
            }else{
                $data['pic'] = 'default.jpg';
            }
        }

        // dd($data);
        $res = DB::table('users') -> insert($data);
        if($res)
        {
            return redirect('./admin/user/index') -> with(['info' => '添加成功']);
        }else{
            return back() -> with(['info' => '添加失败']);
        }
    }

    // index
    public function index(Request $request)
    {
        // var_dump($request -> all())
        // 查询数据
        // $data = DB::table('users') -> where('name', 'like', '%'.$request -> input ('keywords').'%') -> paginate($request -> input('num', 10));
        //
        $data = DB::table('users') -> where(function($query) use ($request){
            $query -> where('name', 'like', '%'.$request -> input('keywords').'%');
        }) -> paginate($request -> input('num', 10));

        return view('admin.user.index', ['data' => $data, 'request' => $request -> all()]);
    }

    // ajax修改用户状态
    public function ajaxStatus(Request $request)
    {
        $id = $request -> input('id');
        // 查询
        $status = DB::table('users') -> where('id', $id) -> first() -> status;

        // 判断
        if($status == 0)
        {
            $res = DB::table('users') -> where('id', $id) -> update(['status' => 1]);

            if($res)
            {
                return 1;
            }else{
                return 2;
            }
        }elseif($status == 1)
        {
           $res = DB::table('users') -> where('id', $id) -> update(['status' => 0]);
            if($res)
            {
                return 0;
            }else{
                return 2;
            }
        }
    }

    // 双击修改用户名
    public function ajaxName(Request $request)
    {
        // return 111;
        $id = $request -> id;
        $name = $request -> name;

       $data = DB::table('users') -> where('name', $name) -> first();

       if($data)
       {
            return 4;
       }else
       {
            $res = DB::table('users') -> where('id', $id) -> update(['name' => $name]);
            if($res)
            {
                return 1;
            }else{
                return 0;
            }
       }
    }

    // edit
    public function edit($id)
    {
        // echo $id;
        $data = DB::table('users') -> where('id', $id) -> first();
        return view('admin.user.edit', ['data' => $data, 'title' => '用户编辑']);
    }

    // update
    public function update(Request $request)
    {
        $data = $request -> except('_token', 'id');
        // dd($data);

        // 获取原来的图片
        $oldPic = DB::table('users') -> where('id', $request -> id) -> first() -> pic;
        if($request -> hasFile('pic'))
        {
            if($request -> file('pic') -> isValid())
            {
                $suffix = $request -> file('pic') -> getClientOriginalExtension();
                $fileName = time().mt_rand(10000,99999).'.'.$suffix;
                // 移动文件
                $move = $request -> file('pic') -> move('./uploads/yhtx',$fileName);
                if($move)
                {
                    $data['pic'] = $fileName;
                    // 删除原来的图片
                    unlink('./uploads/yhtx/'.$oldPic);
                }
            }
        }

        // 执行修改
        $res = DB::table('users') -> where('id', $request -> id) -> update($data);

        if($res)
        {
            return redirect('admin/user/index') -> with(['info' => '修改成功']);
        }else{
            return back() -> with(['info' => '修改失败']);
        }
    }

    // 删除
    public function delete($id)
    {

        // 获取原来的图片
        $oldPic = DB::table('users') -> where('id', $id) -> first() -> pic;
        $res = DB::table('users') -> delete($id);
        if($res)
        {
            // 删除图片
            if(file_exists('./uploads/yhtx/'.$oldPic))
            {
                unlink('./uploads/yhtx/'.$oldPic);
            }
            return redirect('admin/user/index') -> with(['info' => '删除成功']);
        }else{
            return back() -> with(['info' => '删除失败']);
        }
    }

}
